package server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.rmi.server.RMIServerSocketFactory;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class RMISSLServerSocketFactory implements RMIServerSocketFactory, Serializable {
	/*
	 *  permission java.io.FilePermission "/-", "read";
    	permission java.net.AllPermission;
	 */
	private static final long serialVersionUID = 1L;

	public ServerSocket createServerSocket(int port) throws IOException
    { 
	   SSLServerSocket ss = null;
	   SSLServerSocketFactory ssf = null;
	   try {
	       	// set up key manager to do server authentication
       		SSLContext ctx;
       		KeyManagerFactory kmf;
       		TrustManagerFactory tmf;
	       	KeyStore ks, ts;
	       	char[] filepassphrase = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
	    	char[] keypassphrase = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();

	     	ctx = SSLContext.getInstance("TLS");
	       	kmf = KeyManagerFactory.getInstance("SunX509");
            tmf = TrustManagerFactory.getInstance("SunX509");
	       	ks = KeyStore.getInstance("JKS");
	       	ts = KeyStore.getInstance("JKS");

	       	ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), filepassphrase);
	       	ts.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), keypassphrase);
	       	kmf.init(ks, keypassphrase);
	       	tmf.init(ts);
       		ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

      		ssf = ctx.getServerSocketFactory();
	    } catch (Exception e) {
       		e.printStackTrace();
	    }
	    ss = (SSLServerSocket) ssf.createServerSocket(port);
	    ss.setNeedClientAuth(true);
		return ss;
	 }
}
